using System;
using MessagePack;
using MessagePack.Resolvers;
using Microsoft.Extensions.Logging;
using Mytek.Messenger.Serializers.MessagePackSerializer;
using ObjectSerializers.Abstractions;

namespace ObjectSerializers.MessagePackSerializer
{
    public class Context : BasicSerializerContext
    {
        public Context(ILogger<Context> logger)
            : base(logger)
        {
            var resolver = CompositeResolver.Create(new[]
                {
                    new DurableDateTimeFormatter()
                },
                new[] { StandardResolver.Instance });

            var options = MessagePackSerializerOptions.Standard.WithResolver(resolver);

            MessagePack.MessagePackSerializer.DefaultOptions = options;
        }

        protected override ReadOnlyMemory<byte> OnSerialize<T>(T value)
        {
            return MessagePack.MessagePackSerializer.Serialize(value, MessagePack.MessagePackSerializer.DefaultOptions);
        }

        protected override T OnDeserialize<T>(ReadOnlyMemory<byte> buffer)
        {
            return MessagePack.MessagePackSerializer.Deserialize<T>(buffer,
                MessagePack.MessagePackSerializer.DefaultOptions);
        }
    }
}